package myservice.android.utilities;

import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AddressComparator implements Comparator<Record> {
	
	private int extractNumberFromString(String s) {
		Pattern p = Pattern.compile("-?\\d+");
		Matcher m = p.matcher(s);
		if (m.find()) {
			return Integer.parseInt(m.group());
		} else
			return 0;
	}

	@Override
	public int compare(Record rec1, Record rec2) {	
		
		String string1 = rec1.firstLine;
		String string2 = rec2.firstLine;
		
		int number1 = extractNumberFromString(string1);
		int number2 = extractNumberFromString(string2);			
		
		if (number1==0 && number2!=0)
			return -1;
		
		if 	(number1!=0 && number2==0)
			return 1;
		
		if (number1!=0 && number2!=0) {
			if (number1==number2) { // if identical numbers, order alphabetically
				return string1.compareTo(string2);
			} else
				return number1 - number2;
		}
		
		// None of the strings contains a number; then sort alphabetically
		return string1.compareTo(string2);
		
	}

}
